'''
Created on 6 mars 2011

@author: Maison
'''

import sys

import datetime

from django.utils import simplejson

from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
from google.appengine.ext import db

from be.becloud.utils import encodeToJSON
from be.becloud.missions.Missions import Mission
from be.becloud.contacts.Contacts import Contact
from be.becloud.yards.Yards import Yard

class MainHandler(webapp.RequestHandler):
    def get(self):
        self.response.out.write('Hello world here!')

class AJAXHandler(webapp.RequestHandler):
    def get(self,type):
        all = globals()[type].all()
        self.response.out.write(encodeToJSON(all))
        
    def post(self,type):
        newcontacts = simplejson.load(self.request.body_file)
        items = newcontacts['items']
        saved = []
        for newcontact in items:
            sys.stderr.write('Add '+type+' '+str(newcontact)+'\n')
            item = globals()[type]()
            for property,value in newcontact.iteritems() :
                self.mansetattr(item,property,value)
            item.put()
            saved.append(item)
        self.response.out.write(encodeToJSON({'success' :'true', 'items' : saved }))

    def put(self,type):
        updatedcontacts = simplejson.load(self.request.body_file)
        items = updatedcontacts['items']
        saved = []
        for updatedcontact in items:
            sys.stderr.write('Update '+type+' '+str(updatedcontact)+'\n')
            item = globals()[type].get_by_id(updatedcontact['id'])
            for property,value in updatedcontact.iteritems() :
                self.mansetattr(item,property,value)
            item.put()
            saved.append(item)
        self.response.out.write(encodeToJSON({'success' :'true', 'items' : saved }))

    def delete(self,type):
        todeletecontacts = simplejson.load(self.request.body_file)
        items = todeletecontacts['items']
        for todeletecontact in items:
            sys.stderr.write('Delete '+type+' '+str(todeletecontact)+'\n')
            item = globals()[type].get_by_id(todeletecontact['id'])
            item.delete()
        self.response.out.write(encodeToJSON({'success' :'true' }))
            
            
    def mansetattr(self,item,property,value):
        if property == "id":
            return
        try:
            propType = item._properties[property]
            if isinstance(propType, db.DateProperty):
                value = datetime.datetime.strptime(value,"%Y-%m-%dT%H:%M:%S")
                value = datetime.date(value.year,value.month,value.day)
                setattr(item,property,value)
            elif isinstance(propType, db.DateTimeProperty):
                value = datetime.datetime.strptime(value,"%Y-%m-%dT%H:%M:%S")
                setattr(item,property,value)
            elif isinstance(propType, db.FloatProperty):
                value = float(value)
                setattr(item,property,value)            
            else:
                setattr(item,property,value)
        except KeyError:
            return        
    
def main():
    application = webapp.WSGIApplication([('/service/main', MainHandler),(r'/service/ajax/([A-Za-z]*).*',AJAXHandler)],debug=True)
    util.run_wsgi_app(application)

if __name__ == '__main__':
    main()